//
//  SMHelper.m
//  DiDi
//
//  Created by huangtie on 2017/2/28.
//  Copyright © 2017年 Sinmore. All rights reserved.
//

#import "SMHelper.h"
#import <Photos/Photos.h>

@implementation SMHelper

+ (UIBarButtonItem *)customBackBarItemWithTarget:(id)target action:(SEL)action
{
    return [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back"] style:UIBarButtonItemStylePlain target:target action:action];
}

+ (UIBarButtonItem *)customBarItemWithTitle:(NSString *)title target:(id)target action:(SEL)action
{
    UIButton *button = [[UIButton alloc] init];
    
    [button setTitle:title forState:UIControlStateNormal];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [button setTitleColor:[UIColor colorWithWhite:1 alpha:0.5f] forState:UIControlStateHighlighted];
    [button setTitleColor:[UIColor grayColor] forState:UIControlStateDisabled];
    [button addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
    button.titleLabel.font = [UIFont fontWithName:@"Helvetica" size:14.0];
    [button sizeToFit];
    
    return [[UIBarButtonItem alloc] initWithCustomView:button];
}

+ (UIBarButtonItem *)customBarItemWithImageName:(NSString *)imageName
                                         target:(id)target
                                         action:(SEL)action{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
    [button addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
    [button sizeToFit];
    return [[UIBarButtonItem alloc] initWithCustomView:button];
}

+ (UIBarButtonItem *)searchBarItemWithTarget:(id)target
                                      action:(SEL)action
{
    return [SMHelper customBarItemWithImageName:@"venue_search" target:self action:action];
}

+ (UIBarButtonItem *)collectBarItem:(BOOL)isCollect
                             target:(id)target
                             action:(SEL)action
{
    NSString *imageName = isCollect ? @"venue_collection_s" : @"venue_collection";
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
    [button addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
    [button sizeToFit];
    button.userInteractionEnabled = !isCollect;
    return [[UIBarButtonItem alloc] initWithCustomView:button];
}

+ (NSAttributedString *)textMatchImage:(NSString *)text
                              textFont:(UIFont *)textFont
                             textColor:(UIColor *)textColor
                                 image:(NSString *)image
                            inserIndex:(NSInteger)inserIndex
                               offsetY:(CGFloat)offsetY
                             imageSize:(CGSize)imageSize
{
    NSMutableAttributedString * titleString = [[NSMutableAttributedString alloc] initWithString:text];
    NSTextAttachment * iconAttachment = [[NSTextAttachment alloc] init];
    iconAttachment.image = [UIImage imageNamed:image];
    CGFloat image_w = imageSize.width == 0 ? iconAttachment.image.size.width : imageSize.width;
    CGFloat image_h = imageSize.height == 0 ? iconAttachment.image.size.height : imageSize.height;
    iconAttachment.bounds= CGRectMake(0, offsetY, image_w, image_h);
    if (inserIndex < 0 || inserIndex > titleString.length) {
        inserIndex = 0;
    }
    [titleString insertAttributedString:[NSAttributedString attributedStringWithAttachment:iconAttachment] atIndex:inserIndex];
    [titleString addAttribute:NSForegroundColorAttributeName value:textColor range:NSMakeRange(0, titleString.length)];
    [titleString addAttribute:NSFontAttributeName value:textFont range:NSMakeRange(0, titleString.length)];
    return titleString;
}

+ (NSAttributedString *)textMatchArrowDown:(NSString *)text
{
    NSInteger index = text.length;
    return [SMHelper textMatchImage:text textFont:SCREEN_WIDTH == 320 ? FONT_NORMAL_12 : FONT_NORMAL_14 textColor:UICOLOR_ARGB(0xff333333) image:@"custom_arrow_down" inserIndex:index offsetY:2 imageSize:CGSizeMake(0, 0)];
}

+ (BOOL)checkCameraAuthority:(void (^)(BOOL isPass))callback{
    AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (status == AVAuthorizationStatusNotDetermined) {
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
            if (callback) {
                callback(granted);
            }
        }];
        return NO;
    }else if (status == AVAuthorizationStatusAuthorized){
        if (callback) {
            callback(YES);
        }
        return YES;
    }else{
        if (callback) {
            callback(NO);
        }
        [SMHelper openAuthorityWithString:@"相机"];
        return NO;
    }
}

+ (BOOL)checkPhotoAuthority:(void (^)(BOOL isPass))callback{
    BOOL isSupport = [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary];
    if (isSupport) {
        PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
        if (status == PHAuthorizationStatusNotDetermined) {
            //请求权限
            [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
                BOOL isPass = YES;
                if (status == PHAuthorizationStatusNotDetermined
                    || status == PHAuthorizationStatusRestricted) {
                    isPass = NO;
                }
                if (callback) {
                    callback(isPass);
                }
            }];
            return NO;
        }else if (status == PHAuthorizationStatusAuthorized){
            if (callback) {
                callback(YES);
            }
            return YES;
        }else{
            if (callback) {
                callback(NO);
            }
            [SMHelper openAuthorityWithString:@"相册"];
            return NO;
        }
    }else{
        return NO;
    }
}

//开启权限提醒
+ (void)openAuthorityWithString:(NSString *)string{
    NSString *message = [NSString stringWithFormat:@"%@权限未开启,若想使用%@,请开启%@权限", string, string, string];
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alertController addAction:cancel];
    UIAlertAction *gotoSetting = [UIAlertAction actionWithTitle:@"去开启" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
    }];
    [alertController addAction:gotoSetting];
    [GETWINDOW.rootViewController presentViewController:alertController animated:YES completion:nil];
}

+ (void)buildLayerLine:(UIView *)view
                  edge:(UIEdgeInsets)edge
                 color:(UIColor *)color
{
    if (edge.left > 0) {
        UIBezierPath *leftLinePath = [UIBezierPath bezierPath];
        [leftLinePath moveToPoint:CGPointMake(0 , 0)];
        [leftLinePath addLineToPoint:CGPointMake(0, view.height)];
        
        CAShapeLayer *leftLayer = [[CAShapeLayer alloc] init];
        leftLayer.strokeColor = color.CGColor;
        leftLayer.fillColor = [UIColor clearColor].CGColor;
        leftLayer.lineWidth = edge.left;
        leftLayer.frame = view.bounds;
        leftLayer.path = leftLinePath.CGPath;
        [view.layer addSublayer:leftLayer];
    }
    if (edge.top > 0) {
        UIBezierPath *topLinePath = [UIBezierPath bezierPath];
        [topLinePath moveToPoint:CGPointMake(0 , 0)];
        [topLinePath addLineToPoint:CGPointMake(view.width , 0)];
        
        CAShapeLayer *topLayer = [[CAShapeLayer alloc] init];
        topLayer.strokeColor = color.CGColor;
        topLayer.fillColor = [UIColor clearColor].CGColor;
        topLayer.lineWidth = edge.top;
        topLayer.frame = view.bounds;
        topLayer.path = topLinePath.CGPath;
        [view.layer addSublayer:topLayer];
    }
    if (edge.right > 0) {
        UIBezierPath *rightLinePath = [UIBezierPath bezierPath];
        [rightLinePath moveToPoint:CGPointMake( view.width , 0)];
        [rightLinePath addLineToPoint:CGPointMake(view.width, view.height)];
        
        CAShapeLayer *rightLayer = [[CAShapeLayer alloc] init];
        rightLayer.strokeColor = color.CGColor;
        rightLayer.fillColor = [UIColor clearColor].CGColor;
        rightLayer.lineWidth = edge.right;
        rightLayer.frame = view.bounds;
        rightLayer.path = rightLinePath.CGPath;
        [view.layer addSublayer:rightLayer];
    }
    if (edge.bottom > 0) {
        UIBezierPath *bottomLinePath = [UIBezierPath bezierPath];
        [bottomLinePath moveToPoint:CGPointMake( 0 , view.height)];
        [bottomLinePath addLineToPoint:CGPointMake(view.width, view.height)];
        
        CAShapeLayer *bottomLayer = [[CAShapeLayer alloc] init];
        bottomLayer.strokeColor = color.CGColor;
        bottomLayer.fillColor = [UIColor clearColor].CGColor;
        bottomLayer.lineWidth = edge.bottom;
        bottomLayer.frame = view.bounds;
        bottomLayer.path = bottomLinePath.CGPath;
        [view.layer addSublayer:bottomLayer];
    }
} 

+ (UIImage *)create2Dbarcode:(NSString *)linkString outputSize:(CGSize)size{
    CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    // 2. 恢复滤镜的默认属性
    [filter setDefaults];
    // 3. 将字符串转换成
    NSData *data = [linkString dataUsingEncoding:NSUTF8StringEncoding];
    // 4. 通过KVO设置滤镜inputMessage数据
    [filter setValue:data forKey:@"inputMessage"];
    // 5. 获得滤镜输出的图像
    CIImage *outputImage = [filter outputImage];
    //UIImage *barcodeImage = [UIImage imageWithCIImage:outputImage];
    // 6. 将CIImage转换成UIImage，并放大显示
    CGRect extent = CGRectIntegral(outputImage.extent);
    //设置比例
    CGFloat scale = MIN(size.width * 2 / CGRectGetWidth(extent), size.height * 2 / CGRectGetHeight(extent));
    // 创建bitmap（位图）;
    size_t width = CGRectGetWidth(extent) * scale;
    size_t height = CGRectGetHeight(extent) * scale;
    CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
    CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);
    CIContext *context = [CIContext contextWithOptions:nil];
    CGImageRef bitmapImage = [context createCGImage:outputImage fromRect:extent];
    CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
    CGContextScaleCTM(bitmapRef, scale, scale);
    CGContextDrawImage(bitmapRef, extent, bitmapImage);
    // 保存bitmap到图片
    CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
    CGContextRelease(bitmapRef);
    CGImageRelease(bitmapImage);
    return [UIImage imageWithCGImage:scaledImage];
}

+ (UIImage *)resizableImage:(UIImage *)image
{
    CGFloat top = image.size.height / 2; // 顶端盖高度
    CGFloat bottom = image.size.height / 2 ; // 底端盖高度
    CGFloat left = image.size.width / 2; // 左端盖宽度
    CGFloat right = image.size.height / 2; // 右端盖宽度
    UIEdgeInsets insets = UIEdgeInsetsMake(top, left, bottom, right);
    // 指定为拉伸模式，伸缩后重新赋值
    return [image resizableImageWithCapInsets:insets resizingMode:UIImageResizingModeStretch];
}

@end
